<template>
  <div>
    <!-- 面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>Amazon基础信息</el-breadcrumb-item>
      <el-breadcrumb-item>PO基础信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-col :span='7'>
          <!-- 搜索添加区域-->
          <!-- <el-input placeholder="请输入PO" v-model='queryInfo.query' :clearable='true' @clear='getPOList'>
            <el-button slot="append" icon="el-icon-search" @click='getPOList'></el-button>
          </el-input> -->
          <el-autocomplete class="inline-input"
                           v-model="queryInfo.query"
                           :fetch-suggestions="querySearchPOByExtend"
                           placeholder="请输入PO"
                           @select="handleSelect"
                           :clearable='true'
                           @clear='getPOList'>
            <el-button slot="append"
                       icon="el-icon-search"
                       @click='getPOList'></el-button>
          </el-autocomplete>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click='addPOInfo'>添加PO信息</el-button>
        </el-col>
      </el-row>

      <!--PO列表区域-->
      <el-table :data="POExtendList"
                :border="true"
                :stripe="true"
                :header-cell-style="{'text-align':'center','font-weight':'700','color':'#606266'}"
                :cell-style="{'text-align':'center'}">
        <el-table-column fixed
                         width='50'
                         type="index"></el-table-column>
        <el-table-column fixed
                         width='100'
                         label="PO"
                         prop="PO_NO"></el-table-column>
        <el-table-column width='150'
                         label="LEVELCODE"
                         prop="SERVICE_LEVELCODE"></el-table-column>
        <el-table-column width='150'
                         label="SCAC"
                         prop="SCAC"></el-table-column>
        <el-table-column width='150'
                         label="BILL_LADING"
                         prop="BILL_LADING_NO"></el-table-column>
        <el-table-column width='150'
                         label="LICENSE_PLATE"
                         prop="LICENSE_PLATE"></el-table-column>
        <el-table-column width='80'
                         label="SHIPPINGFROMCODE"
                         prop="SHIPPINGFROMCODE"></el-table-column>
        <el-table-column width='230'
                         label="SHIPPINGFROMNAME"
                         prop="SHIPPINGFROMNAME"></el-table-column>
        <el-table-column width='80'
                         label="SHIPPINGTOCODE"
                         prop="SHIPPINGTOCODE"></el-table-column>
        <el-table-column width='230'
                         label="SHIPPINGTONAME"
                         prop="SHIPPINGTONAME"></el-table-column>
        <el-table-column width='150'
                         label="CM_ADDRESS"
                         prop="CM_ADDRESS"></el-table-column>
        <el-table-column width='150'
                         label="CM_CITY"
                         prop="CM_CITY"></el-table-column>
        <el-table-column width='150'
                         label="CM_STATE"
                         prop="CM_STATE"></el-table-column>
        <el-table-column width='150'
                         label="CM_POSTAL"
                         prop="CM_POSTAL"></el-table-column>
        <el-table-column width='150'
                         label="CM_COUNTRY"
                         prop="CM_COUNTRY"></el-table-column>
        <el-table-column width='150'
                         label="CTT_VALUE"
                         prop="CTT_VALUE"></el-table-column>
        <el-table-column label="操作"
                         width="180px;">
          <template slot-scope="scope">
            <!--修改-->
            <el-tooltip content="修改PO"
                        placement="bottom"
                        effect="light"
                        :enterable="false">
              <el-button type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click='editPO(scope.row)'>
              </el-button>
            </el-tooltip>
            <!--删除-->
            <el-tooltip content="删除PO"
                        placement="bottom"
                        effect="light"
                        :enterable="false">
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="deletePO(scope.row.PO_NO)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 2, 5, 10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"
                     background>
      </el-pagination>
    </el-card>

    <!-- 新增PO其他信息-->
    <el-dialog title='添加PO扩展信息'
               :visible.sync="addDialogVisible"
               width="80%"
               @closed='addPOFormClosed'
               :close-on-click-modal='false'>
      <!--内容主体区-->
      <el-form :model="addPOForm"
               :rules="addPOFormRules"
               ref="addPOFormRef"
               label-width='100px'>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='PO_NO'
                          label-width="150px"
                          prop='PO_NO'>
              <!-- <el-input placeholder='请输入PO' v-model='addPOForm.PO' :clearable='true'></el-input> -->
              <el-autocomplete class="inline-input"
                               v-model="addPOForm.PO_NO"
                               :fetch-suggestions="querySearchPO"
                               placeholder="请输入PO"
                               @select="handleSelect"
                               :clearable='true'
                               style="width: 100%;"
                               :trigger-on-focus='false'
                               ref='poautocomplete'>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span='2'></el-col>
          <el-col :span='11'>
            <el-form-item label='Service codes'
                          label-width="150px"
                          prop='SERVICE_LEVELCODE'>
              <el-select v-model='addPOForm.SERVICE_LEVELCODE'
                         filterable
                         remote
                         reserve-keyword
                         placeholder='请输入level code'
                         :remote-method="searchServiceLevelCode"
                         :loading="level_loading"
                         style="width: 100%;">
                <el-option v-for="item in serviceLevelOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"
                           :clearable='true'>
                </el-option>
              </el-select>
              <!-- <el-input v-model='addPOForm.SERVICE_LEVELCODE'></el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='SCAC'
                          label-width="150px"
                          prop='SCAC'>
              <el-input placeholder='请输入SCAC'
                        v-model='addPOForm.SCAC'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='2'></el-col>
          <el-col :span='11'>
            <el-form-item label='BILL_Lading'
                          label-width="150px"
                          prop='BILL_LADING_NO'>
              <el-input placeholder='请输入BILL_LADING'
                        v-model='addPOForm.BILL_LADING_NO'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='BOOKING_NO'
                          label-width="150px"
                          prop='BOOKING_NO'>
              <el-input placeholder='请输入BOOKING_NO'
                        v-model='addPOForm.BOOKING_NO'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='2'></el-col>
          <el-col :span='11'>
            <el-form-item label='LICENSE_PLATE'
                          label-width="150px"
                          prop='LICENSE_PLATE'>
              <el-input placeholder='请输入LICENSE_PLATE'
                        v-model='addPOForm.LICENSE_PLATE'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='Region'
                          label-width="150px"
                          prop='REGION'>
              <!-- <el-input placeholder='请输入Region' v-model='addPOForm.REGION' @blur='regionSearchCodeInfo'></el-input> -->
              <el-select v-model='addPOForm.REGION'
                         placeholder='请选择Region'
                         style="width: 100%;"
                         @change='regionChooseChange'>
                <el-option v-for='item in regionOptions'
                           :key='item.value'
                           :label='item.label'
                           :value='item.value'>
                </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label='Shipping From Code'
                  label-width="150px">
                  <el-input placeholder='请输入SHIPPING FROM CODE' v-model='addPOForm.SHIPPINGFROMCODE'></el-input>
            </el-form-item> -->
          </el-col>
          <el-col :span='2'></el-col>
          <el-col :span='11'>
            <el-form-item label='Shipping From Code'
                          label-width="150px">
              <el-input placeholder='请输入SHIPPING FROM CODE'
                        v-model='addPOForm.SHIPPINGFROMCODE'
                        :disabled='true'>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='Shipping From name'
                          label-width="150px">
              <el-input placeholder='请输入SHIPPING FROM NAME'
                        v-model='addPOForm.SHIPPINGFROMNAME'
                        :disabled='true'>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span='2'></el-col>
          <el-col :span='11'>
            <el-form-item label='Shipping To Code'
                          label-width="150px"
                          prop='SHIPPINGTOCODE'>
              <el-input placeholder='请输入SHIPPING TO CODE'
                        v-model='addPOForm.SHIPPINGTOCODE'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='Shipping To name'
                          label-width="150px"
                          prop='SHIPPINGTONAME'>
              <!-- <el-input placeholder='请输入SHIPPING TO NAME'
                        v-model='addPOForm.SHIPPINGTONAME'>
              </el-input> -->
              <el-select v-model='addPOForm.SHIPPINGTONAME'
                         placeholder='请输入SHIPPING TO NAME'
                         style="width: 100%;">
                <el-option v-for='item in ShippingToNames'
                           :key='item.value'
                           :label='item.label'
                           :value='item.value'>
                </el-option>
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span='2'></el-col>
          <el-col :span='11'>
            <el-form-item label='CM ADDRESS'
                          label-width="150px"
                          prop='CM_ADDRESS'>
              <el-input placeholder='请输入CM ADDRESS'
                        v-model='addPOForm.CM_ADDRESS'
                        :disabled='true'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='CM CITY'
                          label-width="150px"
                          prop='CM_CITY'>
              <el-input placeholder='请输入CM CITY'
                        v-model='addPOForm.CM_CITY'
                        :disabled='true'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='2'></el-col>
          <el-col :span='11'>
            <el-form-item label='CM STATE'
                          label-width="150px"
                          prop='CM_STATE'>
              <el-input placeholder='请输入CM STATE'
                        v-model='addPOForm.CM_STATE'
                        :disabled='true'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='CM POSTAL'
                          label-width="150px"
                          prop='CM_POSTAL'>
              <el-input placeholder='请输入CM POSTAL'
                        v-model='addPOForm.CM_POSTAL'
                        :disabled='true'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='2'></el-col>
          <el-col :span='11'>
            <el-form-item label='CM COUNTRY'
                          label-width="150px"
                          prop='CM_COUNTRY'>
              <el-input placeholder='请输入CM COUNTRY'
                        v-model='addPOForm.CM_COUNTRY'
                        :disabled='true'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type='flex'>
          <el-col :span='11'>
            <el-form-item label='CTT_VALUE'
                          label-width="150px"
                          prop='CTT_VALUE'>
              <el-input placeholder='请输入CTT_VALUE'
                        v-model='addPOForm.CTT_VALUE'></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!--底部区-->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click='addPOContent'>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    const validatePO = async (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入PO'))
      } else {
        const isExist = await this.checkPOExtendExist(value)
        console.log(isExist)
        if (isExist) {
          callback(new Error(`${value}已经维护过资料,不允许重复维护`))
        } else {
          const poNameList = this.poInfoFromTT.map(item => {
            return item.PO
          })
          // 再检查是否存在再TT中,如果不存在则继续报错
          if (poNameList.indexOf(value) <= 0) {
            callback(new Error(`${value}在TT中找不到资料，请检查`))
          } else {
            callback()
          }
        }
      }
    }

    return {
      addDialogVisible: false, // 控制是否显示新增用户的dialog
      serviceLevelOptions: [], // Service LevelCode下拉选项
      serviceLevelTotalOptions: [], // Service LevelCode总Total
      regionOptions: [], // Region下拉选项
      ShippingToNames: [], // 根据region获取对应shippingtoname的选项
      level_loading: false, // Service LevelCode Loading效果
      // 获取PO列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      POExtendList: [], // POExtend汇总数据
      poInfoFromTT: [],
      poInfoFromDB: [], // 从越南库中获取到的PO信息
      poListFromDB: [],
      poList: [],
      total: 0,
      addPOForm: {
        PO_NO: '',
        SERVICE_LEVELCODE: '',
        SCAC: '',
        BILL_LADING_NO: '',
        BOOKING_NO: '',
        LICENSE_PLATE: '',
        REGION: '',
        SHIPPINGFROMCODE: '',
        SHIPPINGFROMNAME: '',
        SHIPPINGTOCODE: '',
        SHIPPINGTONAME: '',
        CM_ADDRESS: 'Building 2,Lot T, Quang Chau Industrial Park, Quang Chau commune',
        CM_CITY: 'Viet Yen district',
        CM_STATE: 'Bac Giang province',
        CM_POSTAL: '210000',
        CM_COUNTRY: 'VN',
        CTT_VALUE: ''
      },
      // 添加表单应用规则
      addPOFormRules: {
        PO_NO: [{
          required: true,
          validator: validatePO,
          trigger: ['blur', 'change']
        }],
        SERVICE_LEVELCODE: [{
          required: true,
          message: '请输入Service Level Code',
          trigger: ['blur', 'change']
        }],
        SCAC: [{
          required: true,
          message: '请输入SCAC',
          trigger: 'blur'
        }],
        BILL_LADING_NO: [{
          required: true,
          message: '请输入BILL_LADING_NO',
          trigger: 'blur'
        }],
        BOOKING_NO: [{
          required: true,
          message: '请输入BOOKING_NO',
          trigger: 'blur'
        }],
        LICENSE_PLATE: [{
          required: true,
          message: '请输入LICENSE_PLATE',
          trigger: 'blur'
        }],
        REGION: [{
          required: true,
          message: '请输入REGION',
          trigger: ['blur', 'change']
        }],
        SHIPPINGTOCODE: [{
          required: true,
          message: '请输入SHIPPINGTOCODE',
          trigger: 'blur'
        }],
        SHIPPINGTONAME: [{
          required: true,
          message: '请输入SHIPPINGTONAME',
          trigger: 'blur'
        }],
        CM_ADDRESS: [{
          required: true,
          message: '请输入CM_ADDRESS',
          trigger: 'blur'
        }],
        CM_CITY: [{
          required: true,
          message: '请输入CM_CITY',
          trigger: 'blur'
        }],
        CM_STATE: [{
          required: true,
          message: '请输入CM_STATE',
          trigger: 'blur'
        }],
        CM_POSTAL: [{
          required: true,
          message: '请输入CM_POSTAL',
          trigger: 'blur'
        }],
        CM_COUNTRY: [{
          required: true,
          message: '请输入CM_COUNTRY',
          trigger: 'blur'
        }],
        CTT_VALUE: [{
          required: true,
          message: '请输入CTT_VALUE',
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    querySearchPO (queryString, cb) {
      var poInfoList = this.poInfoFromTT
      var currentPOList = []
      for (let index = 0; index < poInfoList.length; index++) {
        const item = {}
        item.value = poInfoList[index].VALUE
        currentPOList.push(item)
      }
      currentPOList = this.getUniqueArray(currentPOList)
      var results = queryString ? currentPOList.filter(this.createStateFilter(queryString)) : currentPOList
      cb(results)
      this.$refs.poautocomplete.handleFocus()
    },
    querySearchPOByExtend (queryString, cb) {
      var poInfoDBList = this.poInfoFromDB
      var currentPOListDB = []
      for (let index = 0; index < poInfoDBList.length; index++) {
        const item = {}
        item.value = poInfoDBList[index].PO
        currentPOListDB.push(item)
      }
      console.log(currentPOListDB)
      var results = queryString ? currentPOListDB.filter(this.createStateFilter(queryString)) : currentPOListDB
      cb(results)
    },
    createStateFilter (queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    async getPOList () {
      const {
        data: res
      } = await
          this.$http.post('/Amazon/AmazonBaseInfo/SearchPOExtendList', this.queryInfo)
      if (res.meta.status !== 200) {
        return this.$message.error('获取PO列表失败')
      }
      this.$message.success('获取PO列表成功')
      this.POExtendList = res.data.users
      console.log(this.POExtendList)
      this.total = res.data.total
    },
    // 监听pageSize改变的事件
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getPOList()
      console.log(`每页 ${val} 条`)
    },
    // 监听页码值改变事件
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getPOList()
      console.log(`当前页: ${val}`)
    },
    handleSelect (item) {
      // console.log(item)
    },
    querySearch () {

    },
    // 获取去重后的Array
    getUniqueArray (array) {
      const hash = []
      for (let i = 0; i < array.length; i++) {
        for (let j = i + 1; j < array.length; j++) {
          if (array[i].value === array[j].value) {
            ++i
          }
        }
        hash.push(array[i])
      }
      return hash
    },
    // 打开新增弹窗
    addPOInfo () {
      this.addDialogVisible = true
    },
    addPOFormClosed () {
      this.$refs.addPOFormRef.resetFields()
    },
    // 获取Region联动
    regionChooseChange (query) {
      if (query !== '') {
        this.addPOForm.SHIPPINGFROMCODE = query.split('|')[0]
        this.addPOForm.SHIPPINGFROMNAME = query.split('|')[1]
        var that = this
        // 修改shippingtoname的option选项
        const regionWholeContents = this.$store.state.regionList
        regionWholeContents.map(item => {
          if ((item.VENDOR_CODE + '|' + item.COMPANY_NAME) === query) {
            that.ShippingToNames = item.EATTRIBUTE01.split('|').map(subItem => {
              return {
                value: `${subItem}`,
                label: `${subItem}`
              }
            })
          }
        })
      }
    },
    // 从TT中获取所有PO的信息
    async loadAllPOFromTT () {
      const {
        data: res
      } =
        await this.$http.get('/Amazon/AmazonBaseInfo/SearchPOListFromTT')
      if (res.meta.status !== 200) {
        return this.$message.error('从TT获取PO信息失败')
      }
      this.poInfoFromTT = res.data
    },
    // 从越南库中获取所有PO信息
    async loadAllPOFromExtend () {
      const {
        data: res
      } = await this.$http.get('/Amazon/AmazonBaseInfo/SearchPOListFromMES')
      if (res.meta.status !== 200) {
        return this.$message.error('从越南库中获取PO信息失败')
      }
      this.poInfoFromDB = res.data
    },
    async loadAllServiceLevelCode () {
      const {
        data: res
      } = await this.$http.get('/Amazon/AmazonBaseInfo/SearchServiceLevelCode', {
        params: {
          type: 'SERVICE_LEVELCODE',
          program: 'AMAZON_POEXTEND'
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('从后台获取ServiceLevelCode信息失败')
      }
      this.serviceLevelTotalOptions = res.data.PARAM_VALUE.split(';').map(item => {
        return {
          value: `${item}`,
          label: `${item}`
        }
      })
    },

    // 从后台获取ServiceLevelCode资料
    async searchServiceLevelCode (query) {
      if (query !== '') {
        this.level_loading = true
        setTimeout(() => {
          this.level_loading = false
          this.serviceLevelOptions = this.serviceLevelTotalOptions.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.serviceLevelOptions = []
      }
    },
    async regionSearchCodeInfo () {
      const {
        data: res
      } = await this.$http.get('/Amazon/AmazonBaseInfo/SearchShippingInfo')
      // 先存入vuex中
      this.$store.commit('generalAmazonRegionList', res.data)
      this.regionOptions = res.data.map(item => {
        return {
          value: `${item.VENDOR_CODE}|${item.COMPANY_NAME}`,
          label: `${item.REGION}`
        }
      })
      // 获取所有的ShippingTo的信息。将对应关系存在vuex中
      // 然后在change事件中再移除非选中项的数组record
      this.ShippingToNames = res.data.map(item => {
        return {
          value: `${item.EATTRIBUTE01}`,
          label: `${item.EATTRIBUTE01}`
        }
      })
    },
    async checkPOExtendExist (po) {
      const {
        data: res
      } = await this.$http.get('/Amazon/AmazonBaseInfo/CheckPOExtendExist', {
        params: {
          po_no: po
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error('检查PO资料信息失败，请检查网络状况')
        return true
      }
      return res.data
    },
    // 将PO extend信息保存到数据库
    addPOContent () {
      this.$refs.addPOFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const {
          data: res
        } = await this.$http.post('/Amazon/AmazonBaseInfo/InsertAmazonBaseInfo', this.addPOForm)
        if (res.meta.status !== 200) {
          // 添加PO失败
          return this.$message.error('添加PO信息失败')
        }
        this.$message.success('添加PO信息成功')
        this.addDialogVisible = false
        this.getPOList()
      })
    },
    deletePO (obj) {
      this.$confirm('此操作将永久删除该PO, 是否继续?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {
          data: res
        } = await
            this.$http.delete('/Amazon/AmazonBaseInfo/DeletePOInfo', {
              params: {
                PO_NO: obj
              }
            })
        if (res.meta.status !== 200) {
          this.$message.error('删除PO数据失败')
          return
        }
        // 更新用户列表
        this.$message.success('删除PO数据成功')
        this.getPOList()
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },
    editPO (obj) {
      this.$message({
        message: `${obj.PO_NO} 修改功能暂时还没有开发`,
        type: 'warning'
      })
    }
  },
  created () {
    this.getPOList()
    this.loadAllPOFromTT() // 从TT中获取所有PO
    this.loadAllPOFromExtend() // 从越南库中获取PO信息
    this.loadAllServiceLevelCode()
    this.regionSearchCodeInfo() // 获取所有region信息
    // console.log(this.serviceLevelTotalOptions)
  },
  mounted () {

  }
}

</script>
<style lang="less" scoped>
</style>
